'use client';

import React, { useState, useEffect } from 'react';
import { Typography, Button, Space, message } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import { useRouter } from 'next/navigation';
import UserList from '@/components/UserList';
import UserFilters from '@/components/UserFilters';
import ProtectedRoute from '@/components/ProtectedRoute';
import { useAuth } from '@/contexts/AuthContext';
import { addAuthHeader } from '@/utils/auth';
import { User, UserFilters as UserFiltersType, PaginatedResponse, ApiResponse } from '@/types/user';

const { Title } = Typography;

const UsersPage: React.FC = () => {
  const router = useRouter();
  const { user: currentUser } = useAuth();
  const [users, setUsers] = useState<User[]>([]);
  const [loading, setLoading] = useState(false);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });
  const [filters, setFilters] = useState<UserFiltersType>({});

  // 获取用户列表
  const fetchUsers = async (page = 1, pageSize = 10, currentFilters = filters) => {
    setLoading(true);
    try {
      const params = new URLSearchParams({
        page: page.toString(),
        pageSize: pageSize.toString(),
      });

      // 添加过滤参数
      if (currentFilters.status?.length) {
        params.append('status', currentFilters.status.join(','));
      }
      if (currentFilters.role?.length) {
        params.append('role', currentFilters.role.join(','));
      }
      if (currentFilters.department?.length) {
        params.append('department', currentFilters.department.join(','));
      }
      if (currentFilters.search) {
        params.append('search', currentFilters.search);
      }

      const response = await fetch(`/api/users?${params}`, {
        headers: addAuthHeader(),
      });
      const result: ApiResponse<PaginatedResponse<User>> = await response.json();

      if (result.success) {
        setUsers(result.data.data);
        setPagination({
          current: result.data.page,
          pageSize: result.data.pageSize,
          total: result.data.total,
        });
      } else {
        message.error(result.message || '获取用户列表失败');
      }
    } catch (error) {
      console.error('获取用户列表失败:', error);
      message.error('获取用户列表失败');
    } finally {
      setLoading(false);
    }
  };

  // 处理过滤器变化
  const handleFiltersChange = (newFilters: UserFiltersType) => {
    setFilters(newFilters);
    fetchUsers(1, pagination.pageSize, newFilters);
  };

  // 处理分页变化
  const handlePaginationChange = (page: number, pageSize: number) => {
    fetchUsers(page, pageSize);
  };

  // 创建新用户
  const handleCreateUser = () => {
    router.push('/users/create');
  };

  // 查看用户详情
  const handleViewUser = (user: User) => {
    router.push(`/users/${user.id}`);
  };

  // 编辑用户
  const handleEditUser = (user: User) => {
    router.push(`/users/${user.id}/edit`);
  };

  // 删除用户
  const handleDeleteUser = async (userId: string) => {
    try {
      const response = await fetch(`/api/users/${userId}`, {
        method: 'DELETE',
        headers: addAuthHeader(),
      });
      const result: ApiResponse<null> = await response.json();

      if (result.success) {
        message.success('用户删除成功');
        fetchUsers(pagination.current, pagination.pageSize);
      } else {
        message.error(result.message || '删除用户失败');
      }
    } catch (error) {
      console.error('删除用户失败:', error);
      message.error('删除用户失败');
    }
  };

  // 更新用户状态
  const handleUpdateUserStatus = async (userId: string, status: any) => {
    try {
      const response = await fetch(`/api/users/${userId}`, {
        method: 'PUT',
        headers: addAuthHeader({
          'Content-Type': 'application/json',
        }),
        body: JSON.stringify({ status }),
      });
      const result: ApiResponse<User> = await response.json();

      if (result.success) {
        message.success('用户状态更新成功');
        fetchUsers(pagination.current, pagination.pageSize);
      } else {
        message.error(result.message || '更新用户状态失败');
      }
    } catch (error) {
      console.error('更新用户状态失败:', error);
      message.error('更新用户状态失败');
    }
  };

  // 初始化加载数据
  useEffect(() => {
    fetchUsers();
  }, []);

  return (
    <ProtectedRoute requiredRoles={['admin', 'manager']}>
      <div>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 24 }}>
          <Title level={3} style={{ margin: 0 }}>
            用户列表
          </Title>
          {currentUser?.role === 'admin' && (
            <Button
              type="primary"
              icon={<PlusOutlined />}
              onClick={handleCreateUser}
              size="large"
            >
              创建用户
            </Button>
          )}
        </div>

        <UserFilters
          filters={filters}
          onFiltersChange={handleFiltersChange}
          loading={loading}
        />

        <UserList
          users={users}
          loading={loading}
          pagination={pagination}
          onPaginationChange={handlePaginationChange}
          onViewUser={handleViewUser}
          onEditUser={handleEditUser}
          onDeleteUser={handleDeleteUser}
          onUpdateUserStatus={handleUpdateUserStatus}
        />
      </div>
    </ProtectedRoute>
  );
};

export default UsersPage; 